package com.zmzncs.lmtc.common.util;

import com.alibaba.fastjson.JSONObject;
import com.zmzncs.lmtc.common.config.ClientConfig;
import com.zmzncs.lmtc.common.pojo.Rest;
import com.zmzncs.lmtc.common.pojo.tengda.CarInForm;
import com.zmzncs.lmtc.common.pojo.tengda.TengdaForm;
import com.zmzncs.lmtc.module.customer.service.CardService;
import com.zmzncs.lmtc.module.order.service.OrderInfoService;
import com.zmzncs.lmtc.module.park.service.ParkService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * mqtt回调处理类
 */
@Slf4j
@Component
//public class CallbackUtil implements MqttCallbackExtended {
public class CallbackUtil implements MqttCallback {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private ParkService parkService;
    @Autowired
    private CardService cardService;
    @Autowired
    private ClientConfig clientConfig;

    public static CallbackUtil callbackUtil ;

    @PostConstruct //通过@PostConstruct实现初始化bean之前进行的操作
    public void init() {
        System.out.println("初始化");
        callbackUtil = this;
        callbackUtil.orderInfoService = orderInfoService;
    }

    /**
     * 断开重连
     */
    @Override
    public void connectionLost(Throwable cause) {
        log.info("连接断开，发起重连", cause);
        try {
            if (!clientConfig.getClient().isConnected()) {
                clientConfig.getClient().reconnect();
                log.error("尝试重新连接");
            } else {
                clientConfig.getClient().connect(ClientConfig.options);
                log.error("尝试建立新连接");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 接收到消息调用令牌中调用
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

//        log.info("发送消息回调：【{}】", token.isComplete());
    }

    /**
     * 收到消息
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {
        TengdaForm tengdaForm = new TengdaForm();
        try {
            tengdaForm = JSONObject.parseObject(new String(mqttMessage.getPayload()), TengdaForm.class);
        } catch (Exception e) {
            log.info("非对象，不能解析【{}】", new String(mqttMessage.getPayload()));
        }

        //  不打印心跳
        if(!topic.equals("cloud/internet/time") && !(tengdaForm.getServiceId() != null && tengdaForm.getServiceId().equals("sync.park.online.status"))){
            log.info("收到消息（主题：【{}】，Qos：【{}】，内容：【{}】）", topic, mqttMessage.getQos(),  new String(mqttMessage.getPayload()));
        }

        try {
            if(tengdaForm.getServiceId() != null){
                //  不打印心跳
                if(!tengdaForm.getServiceId().equals("sync.park.online.status")) {
                    log.info("serviceId【{}】", tengdaForm.getServiceId());
                }

                //  入场
                if(tengdaForm.getServiceId().equals("sync.enter.in.record")){
                    callbackUtil.orderInfoService.carInPark(tengdaForm);
                }

                //  实时订单
                if(tengdaForm.getServiceId().equals("pay.queryfeebyplate")){
                    callbackUtil.orderInfoService.queryCurrOrder(tengdaForm);
                }

                //  出场支付
                if(tengdaForm.getServiceId().equals("sync.pre.out.record")){
                    callbackUtil.orderInfoService.carOutPay(tengdaForm);
                }

                //  停车订单支付通知
                if(tengdaForm.getServiceId().equals("pay.payparkingfeeorder")){
                    callbackUtil.orderInfoService.payParkingFeeOrder(tengdaForm);
                }

                //  出场
                if(tengdaForm.getServiceId().equals("sync.leave.out.record") || tengdaForm.getServiceId().equals("sync.manualopengate.record")){
                    callbackUtil.orderInfoService.carOutPark(tengdaForm);
                }

                //  获取所有通道信息
                if(tengdaForm.getServiceId().equals("manage.channels")){
                    callbackUtil.parkService.allChannels(tengdaForm);
                }

                // 获取车辆类型
                if(tengdaForm.getServiceId().equals("manage.cartypes")){
                    callbackUtil.parkService.carTypes(tengdaForm);
                }

                //  车辆管理
                if(tengdaForm.getServiceId().equals("manage.cars")){
                    if(tengdaForm.getAction().equals("add")){
                        callbackUtil.cardService.addCars(tengdaForm);
                    }
                    if(tengdaForm.getAction().equals("query")){
                        callbackUtil.cardService.manageCars(tengdaForm);
                    }
                    if(tengdaForm.getAction().equals("edit")){
                        callbackUtil.cardService.editCars(tengdaForm);
                    }
                }

                //  获取固定车列表
                if(tengdaForm.getServiceId().equals("pay.querymonthcardlist")){
                    callbackUtil.cardService.monthCardList(tengdaForm);
                }
            }
        } catch (Exception e) {
            log.info("消息处理错误", e);
        }

    }

    /**
     * 连接后订阅主题
     */
//    @Override
//    public void connectComplete(boolean b, String s) {
//        try {
//            if (null != topic && null != qos) {
//                if (client.isConnected()) {
//                    log.info("连接成功，客户端ID：" + PropertiesUtil.MQTT_CLIENT_ID);
//                    log.info("订阅主题：{}，qos：{}", Arrays.toString(topic), qos);
//                    client.subscribe(topic, qos);
//                } else {
//                    log.info("连接失败，客户端ID：" + PropertiesUtil.MQTT_CLIENT_ID);
//                }
//            }
//        } catch (Exception e) {
//            log.error("订阅主题异常:" + e);
//            e.printStackTrace();
//        }
//    }


}